<link rel="stylesheet" href="__PUBLIC__/plugs/bootstrap-select/css/bootstrap-select.css">
<script type="text/javascript" src="__PUBLIC__/plugs/layer/layer.js"></script>
<script type="text/javascript" src="__PUBLIC__/plugs/bootstrap-select/js/bootstrap-select.js"></script>
<div class="modal fade" id="create-lower-modal">
	<div class="modal-dialog" role="document">
	   <div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
				<span style="font-size: 20px;"><span id="referralname">下放</span></span>
			</div>
			<div class="modal-body">
				<div data-bind="visible: loading" class="loading-panel" style="display: none;">
					<i class="fa fa-spin fa-spinner"></i>
				</div>
				<form class="form-horizontal lower-modelform">
					
					<div class="form-group">
						<label class="control-label col-sm-2">员工</label>
						<div class="col-sm-8">
							<select class="selectpicker multipleSelete" name="power" multiple>
                                {foreach name="userlist2" item="vo" key="k" }
                                {if checkAuthRule('distribution_receive',0,$k)}
								<option value="{$k}">{$vo}</option>
                                {/if}
                                {/foreach}                     
							</select>
						</div>
					</div>
				</form>
			</div>
			<div class="modal-footer">
				<button type="button" id="creaPower" class="btn btn-primary ">提交</button>
			</div>
	   </div>
   </div>
</div>
<script>

$(function(){
    // $(".toolTip [title]").tooltipify();

    leftMenuNum();

    //展开功能
    var BN_height;
	if(GetQueryString('book_id')){
		$('.spread span').show()
		$('.bookName').animate({ height: $('.bookName').height()+2+"px" })
		$('.spread span').text('收回')
	}
	if ($('.bookName').height() > 60) {
		BN_height = $('.bookName').height()
		$('.bookName').height('62') 
		$('.spread span').show()
	}
	$('.spread span').click(function () {
		let status = $('.spread span').text().trim()
		if (status == '展开') {
            $('.bookName').animate({ height: BN_height+2+"px" })
            $('.spread span').text('收回')
		} else {
            $('.bookName').animate({ height: "62px" })
            $('.spread span').text('展开')
        }
	})
});
//排序
function pub_sort(sort){
    window.location.href='{$jumpurl}'+"&pub_sort="+sort;
}

//加入编辑台
function follow(ee, id){
    var url = "{:url('addFollow')}";
    $.ajax({
        type: "POST",
        url: url,
        data:{id:id},
        dataType: "json",
        success: function(data){
            if(data.code==1){
                layer.msg(data.msg);
                setTimeout(function() {	
                    window.location.reload();
                }, 500);
            }else{
                updateAlert("失败，"+data.msg, 'danger');
            }
        },
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        }
    })
}

//编辑功能
function editreferral(ee, rule=''){
    var is_rule = '{:checkAuthRule('edit')}';
    if(!is_rule && rule!='close_rule'){
        layer.msg("你没权限编辑");
        return;
    }

	$("#batchtxt").remove();
	var jsonStr = $(ee).attr('data-json');
	var $modal = $('#create-referral-link-modal');
	$modal.on('shown.bs.modal', function () {
		$("#referralname").html("修改");
		$("#createreferral").html("修改");
		var json =  eval("(" + jsonStr + ")");
		$('#createspreadid').val(json.id);
		$('#content').val(json.content);
        $("input[name='content']").val(json.content);
		$('#score').val(json.score);
        console.log(json)
        $("input[name=title]").val(json.title);
        $("input[name=type]").val(json.type);
		$("input:radio[name=channel][value="+json.channel+"]").attr("checked",true);
		$("input:radio[name=category_id][value="+json.category_id+"]").attr("checked",true);
		$("input:radio[name=book_id][value="+json.book_id+"]").attr("checked",true);
		$("input:radio[name=magnitude_num][value="+json.magnitude_num+"]").attr("checked",true);
		multipleInput(json.platform_ids.split(','),$("input:checkbox[name=platform_ids]"))
		multipleInput(json.tag_ids.split(','),$("input:checkbox[name=tag_ids]"))
        multipleInput(json.hot.split(','),$("input:checkbox[name=hot]"))

	});
	// $modal.on('hide.bs.modal', function () {
	// 	window.location.reload();
	// })
	$modal.modal({backdrop: 'static', keyboard: false})
}
function multipleInput(arr,e){
    if(arr.length!==0){
        arr.forEach((v,index)=>{
            $(e).each((item,elem)=>{
                if(v === $(elem).val()){
                    $(elem).attr("checked",true);
                }
            })
        })
    }
}
//全库下载
function down_all(url){
    var is_rule = '{:checkAuthRule('down_all')}';
    if(!is_rule){
        layer.msg("你没权限下载");
        return;
    }
    window.open(url+"?platform_ids={$platform_id}&type={$typeid}&hot_level={:input('get.hot_level', 999999)}&act={$action}&startdata={$startdata}&enddata={$enddata}");
}
// 左边菜单 显示数量
function leftMenuNum(){
    var url = "{:url('menuNum')}";
    $.ajax({
        type: "POST",
        url:  url,
        data: {'platform_ids':'{$platform_id}', 'type':'{$typeid}'},
        dataType: "json",
        success: function(data){
            if(data.code==0){
                var array = data.data;
                array.forEach(e => {
                    $("#menu_tip_"+e.id).html(e.count)
                });
            }else{
                updateAlert(data.msg, 'danger');
            }
        },
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        }
    })
}

// 获取浏览器参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return r[2];return null;
}

// 过稿功能 
function change_status(id){
    var is_rule = '{:checkAuthRule('status')}';
    if(!is_rule){
        layer.msg("你没权限过稿");
        return;
    }
    $('body').attr("status_id", id);
    var url = "{:url('change_status')}";
    $.ajax({
        type: "POST",
        url: url,
        data:{id:id},
        dataType: "json",
        success: function(data){
            if(data.code==1){
                layer.msg('过稿成功');
                setTimeout(function(){
                    window.location.reload();
                }, 800)
                
            }else{
                
                updateAlert("失败，"+data.msg, 'danger');
            }
        },
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        }
    })
}

// 复制
function copyContent(content, id,reload = true){
    content = content.toString().replace(/<br\/>/g, `
`)
    content = content.replace(/<em>|<\/em>/g,'');
    var oInput = document.createElement('textarea');
    oInput.value = content;
    document.body.appendChild(oInput);
    oInput.select();
    document.execCommand("Copy"); 
    oInput.className = 'oInput';
    oInput.style.display='none';
    let source = '{$action}'
    var url = "{:url('copy')}";
    $.ajax({
        type: "POST",
        url,
        data:{id,source},
        dataType: "json",
        success: function(data){
            if(data.code==1){
                layer.msg('复制成功');
                if(reload){
                    setTimeout(function(){
                        window.location.reload();
                    }, 500)
                }
            }else{
                updateAlert("失败，"+data.msg, 'danger');
            }
        }
    })
}

//上报到公众库
function upload(ee, id){
    var is_rule = '{:checkAuthRule('upload')}';
    if(!is_rule){
        layer.msg("你没权限上报到公众库");
        return;
    }

	$('body').attr("upload_id", id);
	var url = "{:url('uploadMaterial')}";
		$.ajax({
			type: "POST",
			url: url,
			data:{id:id},
			dataType: "json",
			success: function(data){
				if(data.code==1){
					updateAlert(data.msg, 'success');
					setTimeout(function() {	
						window.location.reload();
					}, 1000);
				}else{
					editreferral(ee)
					updateAlert(data.msg, 'danger');
				}
			},
			error : function(e){
				console.log(e.status);
				console.log(e.responseText);
			}
		})
}


//txt下载
function downTxt(content){
    var is_rule = '{:checkAuthRule('down')}';
    if(!is_rule){
        layer.msg("你没权限下载txt");
        return;
    }
    window.open(content);
}
//媒体文件 下载 
function downMedia(content,id, reload = true){
    var is_rule = '{:checkAuthRule('down')}';
    if(!is_rule){
        layer.msg("你没权限下载");
        return;
    }

    let source = '{$action}'
    var url    = "{:url('copy')}";
    $.ajax({
        type: "POST",
        url,
        data:{id,source},
        dataType: "json",
        success: function(data){
            if(data.code==1){
                // layer.msg('下载成功');
                if(reload){
                    setTimeout(function(){
                        window.location.reload();
                    }, 500)
                }
            }else{
                updateAlert("失败，"+data.msg, 'danger');
            }
        }
    });
    // window.location.href=content;
    // window.open(content);
    let aDom = document.createElement('a');
    aDom.style.display = 'none';
    aDom.href = content;
    aDom.setAttribute('download', 'name');
    document.body.appendChild(aDom);aDom.click();
    document.body.removeChild(aDom);
}
// 下放
let inputChecked = []
$('#lower').on('click',function(){
    var is_rule = '{:checkAuthRule('distribution_receive', 0)}';
    inputChecked = []
    if(!is_rule){
        layer.msg("你没权限下放");
        return;
    }
    
    $('input[name="id[]"]:checked').each(function(index, element) {
        inputChecked.push($(element).val())
    });
    if(inputChecked.length === 0){
        layer.msg("请选择素材");
    }else{
        var $modal = $('#create-lower-modal');
        $modal.modal({backdrop: 'static', keyboard: false});
    }
});
$("#creaPower").on('click',function(){

    var is_rule = '{:checkAuthRule('distribution_receive', 0)}';
    if(!is_rule){
        layer.msg("你没权限下放");
        return;
    }
    
    var data = $('.lower-modelform').serializeJson();
    console.log(data)
    var url   = "{:url('distribution_send', 0)}";
    var ids   = inputChecked.toString();
    var uids  = data.power.toString()
    reload = true;
    $.ajax({
        type: "POST",
        url,
        data:{ids, uids},
        dataType: "json",
        success: function(data){
            if(data.code==1){
                layer.msg('下放成功');
                if(reload){
                    setTimeout(function(){
                        window.location.reload();
                    }, 500)
                }
            }else{
                updateAlert("失败，"+data.msg, 'danger');
            }
        }
    });
});
</script>